package com.example.cash.craft.service.impl;

import com.example.cash.craft.dao.persist.repository.IUserRepository;
import com.example.cash.craft.exception.ServiceException;
import com.example.cash.craft.pojo.entity.User;
import com.example.cash.craft.pojo.param.UserRegisterParam;
import com.example.cash.craft.pojo.vo.PageData;
import com.example.cash.craft.pojo.vo.UserVO;
import com.example.cash.craft.service.IUserService;
import com.example.cash.craft.web.StateCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Value("${cash-craft.config.default-page-size}")
    private Integer defaultPageSize;
    @Autowired
    private IUserRepository userRepository;

    @Override
    public void register(UserRegisterParam userRegisterParam) {
        // 检查用户名是否已存在
        int countByUsername = userRepository.countByUsername(userRegisterParam.getUsername());
        if (countByUsername > 0) {
            // 如果用户名已存在，抛出服务异常
            throw new ServiceException(StateCode.ERROR_CONFLICT, "用户名已存在");
        }

        // 创建新用户对象
        User user = new User();
        // 将用户注册参数复制到用户对象
        BeanUtils.copyProperties(userRegisterParam, user);
        // 设置用户非管理员
        user.setIsAdmin(0);

        // 插入用户到数据库
        userRepository.insert(user);
    }

    @Override
    public void deleteById(Long id) {
        // 检查用户ID是否为1，如果是1则抛出服务异常
        if (id == 1) {
            throw new ServiceException(StateCode.ERROR_FORBIDDEN, "不能删除管理员");
        }
        // 根据用户ID查询用户信息
        UserVO findResult = userRepository.selectById(id);
        // 如果用户不存在，则抛出服务异常
        if (findResult == null) {
            throw new ServiceException(StateCode.ERROR_NOT_FOUND, "用户不存在");
        }

        // 删除用户信息
        userRepository.deleteById(id);
    }

    @Override
    public UserVO selectById(Long id) {
        UserVO findResult = userRepository.selectById(id);
        if (findResult == null) {
            throw new ServiceException(StateCode.ERROR_NOT_FOUND, "用户不存在");
        }
        return userRepository.selectById(id);
    }

    @Override
    public PageData<UserVO> listAll(Integer page) {
        return userRepository.listAll(page, defaultPageSize);
    }

}